import subprocess
import datetime
from labmin.webapp.models import Log


class Logger(object):
	version = 0.1

	def __init__(self):
		self.localLog=''
	def printLogLocal(self):
		print self.localLog
	def logLocal(self,std,lstdin):
		if lstdin:
			self.localLog+='<span style="green">> '+lstdin+'</span><br/>\n'
		if std[0]  :
			self.localLog+=std[0]+'<br/>\n'

		if std[1]  :
			self.localLog+='<span style="color:red;">'+std[1]+'</span><br/>\n'
		f=open('/home/slawek/public_html/labmin/logi.log', 'w')
		f.write(self.localLog)

	def logGlobal(self, command, user, host, std):
		entry=Log()
		if command != None:
			if std[1] == None:
				host = host + ' <span style="color:green;">OK</span><br/>\n'
			else:
				host = host + ' <span style="color:red;">FAILED<br/>' + std[1] + '<br/></span>\n'
			entry.description = command + ' ' + user + ' ' + host
			entry.date = datetime.datetime.now()
			entry.save()



class RemoteExecute(object):
	version = 0.1
	def __init__(self,commList,paramList,hostlogin,hIP):
		self.commList=commList
		self.paramList=paramList
		self.hIP=hIP
		self.hostlogin=hostlogin
	
	def resolveParam(self,commands,params):
		f=open('/home/slawek/public_html/labmin/log2.log', 'w')
		commands_tmp = []
		if len(params)>0:
			for command in commands:
				command = command.replace('$$p', params[1],1)
				command = command.replace('$$u', params[0],1)
				commands_tmp.append(command)
				f.write(params[0] + ' ' + params[1]+ ' ' +command+'\n')
		f.close()
		return commands_tmp
	def remoteExec(self):
		
		script=self.resolveParam(self.commList,self.paramList)
		sshHost=self.hostlogin+"@"+self.hIP
		sshHost='root@127.0.0.1'
		print script
		ret= subprocess.Popen(['/bin/bash'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell='True').communicate('ssh  '+sshHost+'\n '+'\n'.join(script)+'\n')
		l=Logger()
		l.logLocal(ret,'\n'.join(script)+'\n')
		return ret[1]
		
	def updateLists(self,commList,paramList):
		self.commList=commList
		self.paramList=paramList
		
	def appendLists(self,commList,paramList):
		self.commList.extend(commList)
		self.paramList.extend(paramList)